package com.cgly.medical.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.cgly.medical.domain.Drug;
import com.cgly.medical.domain.DrugOrder;
import com.cgly.medical.domain.Patient;
import com.cgly.medical.mapper.PatientMapper;
import com.cgly.medical.model.DrugOrderModel;
import com.cgly.medical.service.DelayedSendMessageService;
import com.cgly.medical.service.DrugOrderService;
import com.cgly.medical.service.DrugService;
import com.cgly.medical.util.MailClient;
import com.cgly.medical.util.Msg;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wangxiangli
 * @create 2022-08-24-12:27
 */
@RestController
public class PayController {

//    @Autowired
//    DonaItemService donaItemService;
//    @Autowired
//    DonaService donaService;
    //appid
    private final String APP_ID = "2021000121653555";
    //应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCvm0RZSR+JvEoL9s7sQmGimqd4gBbw+cNlECFYMnj8l8wJcfrnVd8eKGldXGdsKJWZvMeqb/4bkou/FB6rwsSK1cf0T4Q137A83CSULDT18aBAfR8hRrA27XHzLNM85bgXnv6RNrrav7cMWq41vVivv3CiOac928U6byQqdg/jTF6O6XEhncKVsPxnxYEsRy2VhBP3BBrjCwMjKVZ2vRjME1/1hDTI7EesUq6bNrsbWY4hKkqfi7nj8L6RWna7L2+y3uha2sVXXCgpWZIpqyZSOb44zJLpUFCFAj3/GC6IEAuO50qowYoVtjQ0s1a9geyBjcP47h7j5WqL8KkBQU5NAgMBAAECggEAPwZJvIW69PMH3E1jLHYSlopM6rmGAky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Z0N3FMR/y5TFN/fHw6c0J8GrTn0LUuSnQRsSc5GBUxjbSR4b9jHYSQ/mIf2avfzEsCD/BK/6g12jrKrN9fFzqY22iELD5zvE4EAHTeYSX";
    private final String CHARSET = "UTF-8";
    // 支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApcU1Ytgk7Ww/wXDoF3ntMwTVy+QLZNEHKXsx9wESLPRx+JhGETDSfCE5o0neWMhlEfTrFkyrMCqKI50KF9mkHChg3kTckuG9R1hGTmzLLzV50KKsdJvvioqqUX5QMpRgNr+3S8F+uFH5cpLUy+LB9M9GMdG56+OLkCFPMVsSyDfTOTvyqGKno1XzrikrVEk3J9fUrzbQJDnypoY/2C/DMwtc+ZNFfvSfseeTbi8MBk3x0gntRvzmhDUICNPmWPg9JovnZoipVrh1yUqFeQkmQrOX6t/OKZo1350SQC7k7/6jC7pA/G/fZaPKSpY1DnX09s2CClG3LfvQzg6FCNx/6wIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:9090/CGLY/returnUrl";

    @Autowired
    private DrugOrderService drugOrderService;

    @Autowired
    private DelayedSendMessageService delayedSendMessageService;


    @Autowired
    private DrugService drugService;


   @Resource
    PatientMapper patientMapper;

    @Autowired
    MailClient mailClient;



    //必须加ResponseBody注解，否则spring会寻找thymeleaf页面
    @ResponseBody
    @RequestMapping("/pay/alipay/{dona_money}/{dona_id}")
    public String alipay(HttpSession session, Model model,
                        @PathVariable float dona_money,
                        @PathVariable String dona_id) throws AlipayApiException {
        System.out.println("请求进来了############################");
        //把dona_id项目id 放在session中
        session.setAttribute("dona_id",dona_id);

        //生成订单号（支付宝的要求？）
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String user = UUID.randomUUID().toString().replace("-","").toUpperCase();
//        String OrderNum = time+user;
        String OrderNum=dona_id;
        //调用封装好的方法（给支付宝接口发送请求）
        return sendRequestToAlipay(OrderNum,dona_money,"gxjy");
    }
    /*
参数1：订单号
参数2：订单金额
参数3：订单名称
 */
    //支付宝官方提供的接口
    private String sendRequestToAlipay(String outTradeNo,Float totalAmount,String subject) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,APP_ID,APP_PRIVATE_KEY,FORMAT,CHARSET,ALIPAY_PUBLIC_KEY,SIGN_TYPE);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        List<DrugOrder> drugOrders = drugOrderService.getDrugOrderByEndOrderId(outTradeNo);
        Drug drug = drugService.selectDrugByid(drugOrders.get(0).getDrugId().toString());
        Patient patientById = patientMapper.getPatientById(drugOrders.get(0).getPatientId());
        mailClient.sendMail(patientById.getEmail(),"创新骨科医院",patientById.getPname()+"您好，医师已经" +
                "给你开药了，请在两分钟内支付！支付链接如下：http://localhost:9090/CGLY/pay/alipay/"+totalAmount+"/"+outTradeNo);
        // 可填，延时时间，如果填了在此时间段内没有付款则无效，这里的时间支付宝界面上减2分钟
        long etime1 = System.currentTimeMillis() + 4 * 60 * 1000;//延时函数，单位毫秒，这里是延时了3分钟
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String time_expire = df.format(new Date(etime1));

        delayedSendMessageService.send(outTradeNo,120*1000);
        //商品描述（可空）
        String body="";
        subject="药品";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"time_expire\":\"" + time_expire + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }
    @RequestMapping("/returnUrl")
    public void returnUrlMethod(HttpServletRequest request, HttpSession session, Model model) throws AlipayApiException, UnsupportedEncodingException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        //验证签名（支付宝公钥）
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易流水号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            float money = Float.parseFloat(new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8"));

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+money);

            //在这里编写自己的业务代码（对数据库的操作）
			/*
			################################
			*/
            List<DrugOrder> drugOrders = drugOrderService.getDrugOrderByEndOrderId(out_trade_no);
            for(DrugOrder drugOrder:drugOrders){
                DrugOrderModel drugOrderModel=new DrugOrderModel();
                drugOrder.setStatus(1);
                BeanUtils.copyProperties(drugOrder, drugOrderModel);
                drugOrderService.updateDrugOrder(drugOrderModel);
                Drug drug = drugService.selectDrugByid(drugOrder.getDrugId().toString());
                int number = drug.getNumber()-drugOrder.getNumber();
                drug.setNumber(number);
                drugService.updateDrugInfo(drug);
            }
            //跳转到提示页面（成功或者失败的提示页面）
            model.addAttribute("flag",1);
            model.addAttribute("msg","支持");

        }else{
            //跳转到提示页面（成功或者失败的提示页面）
            model.addAttribute("flag",0);
            model.addAttribute("msg","支持");

        }
    }

}
